

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMultiLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Collections;

public class CuratorLock {

    static String MYIP = "192.168.15.132:2181";
    static String MYIPS = "192.168.15.132:2181,192.168.15.132:2182,192.168.15.132:2183";
    static int TIMEOUT = 9000;
    CuratorFramework client;

    /**
     * 创建curator 连接zookeeper
     */
    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(TIMEOUT, 3);
        client = CuratorFrameworkFactory.builder().connectString(MYIPS).sessionTimeoutMs(TIMEOUT).retryPolicy(retryPolicy).namespace("create").build();
        client.start();
    }

    @After
    public void after() {
        client.close();
    }

    /**
     * 排它锁(互斥锁)
     * 当两个互斥锁对象指向同一个路径时,这个两个对象是持有同一把锁的(代码执行过程中是有排他性的)
     */
    @Test
    public void exclusive() {
        //arg1 连接对象
        //arg2 节点路径exclusive
        try {
            InterProcessLock interProcessLock = new InterProcessMutex(client, "/one");
            interProcessLock.acquire();//获取锁
            System.out.println("获取到锁对象!!!");
            interProcessLock.release();//释放锁
            System.out.println("锁释放");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读写锁
     */
    @Test
    public void reaWritLock01() {
        //arg1 连接对象
        //arg2 节点路径exclusive
        try {
            InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/one");
            InterProcessMutex interProcessMutex = lock.readLock();
            interProcessMutex.acquire();

            interProcessMutex.release();

            System.out.println("*****************************************************************");
            InterProcessMutex interProcessMutex1 = lock.writeLock();
            interProcessMutex1.acquire();

            interProcessMutex1.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
